package com.eunion.web.cms.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eunion.common.util.CommUtils;
import com.eunion.core.ExcelUtil;
import com.eunion.core.LogUtil;
import com.eunion.core.common.DeleteVo;
import com.eunion.core.common.JsonVo;
import com.eunion.core.common.response.ResponseList;
import com.eunion.core.exception.ValidateException;
import com.eunion.fileserver.upload.FileInfo;
import com.eunion.web.cms.entity.University;
import com.eunion.web.cms.entity.spec.UniversitySpec;
import com.eunion.web.cms.service.UniversityService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;
import com.eunion.web.common.vo.Web;

/**
 * 大学
 */
@Controller
@RequestMapping("/api/university")
@PreAuthorize("hasAuthority('college:info')")
public class UniversityResource extends BaseTableCommonController<University, Long> {

    @Override
    protected BaseService<University, Long> getBaseService() {
        return universityService;
    }

    @Autowired
    private UniversityService universityService;

    /**
     * 进入专业分类页面
     * 
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/university/university";
    }

    /**
     * 通用的查询接口
     * 
     * @param queryBean
     * @return
     */
    @PostMapping("/findAll")
    @ResponseBody
    public ResponseList<University> findAll(@RequestBody University queryBean) {
        List<University> list = universityService.findAll(UniversitySpec.build(queryBean));
        return new ResponseList<University>(HttpStatus.OK, list);
    }

    /**
     * 学校信息导入
     * 
     * @param obj
     * @param result
     * @param model
     * @param request
     * @return
     */
    @PreAuthorize("hasAuthority('college:import')")
    @PostMapping("/importData")
    public String importData(FileInfo obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            checkBindResult(result);
            if (StringUtils.isNotBlank(obj.getFilepath())) {
                String filepath = obj.getFilepath();
                String fileType = filepath.substring(filepath.lastIndexOf(".") + 1);
                InputStream in = null;

                Workbook wb = null;
                if (fileType.equals("xls")) {
                    in = new FileInputStream(filepath);
                    wb = new HSSFWorkbook(in);
                } else if (fileType.equals("xlsx")) {
                    in = new FileInputStream(filepath);
                    wb = new XSSFWorkbook(in);
                } else {
                    setModuleStatusError(model, "文件格式错误");
                    setModuleImport(model);
                    return getUrlBase().concat("-import");
                }

                // 开始解析数据
                Sheet sheet = wb.getSheetAt(0);
                List<University> list = ExcelUtil.readUniversity(sheet);
                List<University> toSaveUniversity = new ArrayList<>();
                List<University> toUpdateUniversity = new ArrayList<>();
                if (universityService.count() > 0) {
                    for (University university : list) {
                        University queryBean = new University();
                        queryBean.setCode(university.getCode());
                        queryBean.setName(university.getName());
                        List<University> exits = universityService.findAll(UniversitySpec.build(queryBean, true));
                        if (!CommUtils.isEmpty(exits)) {
                            if (exits.size() == 1) {
                                university.setId(exits.get(0).getId());
                                toUpdateUniversity.add(university);
                            } else {
                                // 学校编码为空,名字模糊搜索可能出现列表
                                if (CommUtils.isEmpty(queryBean.getCode())) {
                                    for (University nameU : exits) {
                                        if (queryBean.getName().equals(nameU.getName())) {
                                            if (toUpdateUniversity.contains(university)) {
                                                // 已经存在说明存在冗余
                                                universityService.delete(nameU.getId());
                                            } else {
                                                university.setId(nameU.getId());
                                                toUpdateUniversity.add(university);
                                            }
                                        }
                                    }
                                } else {
                                    // 学校编码不为空,出现多条,则为数据冗余 删除原来的
                                    universityService.delete(exits);
                                    toSaveUniversity.add(university);
                                }
                            }
                        } else {
                            toSaveUniversity.add(university);
                        }

                    }
                }

                // List<University> resultList = getBaseService().save(list);
                if (!CommUtils.isEmpty(toUpdateUniversity)) {
                    for (University update : toUpdateUniversity) {
                        universityService.saveAndFlush(update);
                    }
                }
                List<University> resultList = getBaseService().save(toSaveUniversity);
                if (!CommUtils.isEmpty(toSaveUniversity) && (null == resultList || resultList.size() < 1)) {
                    LogUtil.get(this.getClass()).error("save majorList failed");
                    setModuleStatusOK(model, "导入失败");
                } else {
                    setModuleStatusOK(model, "导入成功");
                }
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "导入失败");
        }
        setModuleImport(model);
        return getUrlBase().concat("-import");
    }

    /**
     * 添加。
     * 表单提交接收对象不能使用@RequestBody
     */
    @PreAuthorize("hasAuthority('college:add')")
    @PostMapping(value = Web.URL_SEP_SAVE, produces = {"application/json;charset=UTF-8"})
    public String save(University obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    if (StringUtils.isNotEmpty(error.getDefaultMessage())) {
                        throw new ValidateException(error.getDefaultMessage());
                    }
                }
            }

            getBaseService().save(obj);
            setModuleStatusOK(model, "添加成功");
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "添加失败");
        }
        setModuleAdd(model);
        return getUrlBase().concat("-add");
    }

    /**
     * 修改。
     * 表单提交接收对象不能使用@RequestBody
     */
    @PostMapping(value = Web.URL_SEP_UPDATE, produces = {"application/json;charset=UTF-8"})
    public String update(University obj, BindingResult result, Model model) {
        try {
            getBaseService().save(obj);
            setModuleStatusOK(model, "修改成功");
        } catch (Exception e) {
            LOG.error("update MajorType error : {}", e);
            setModuleStatusError(model, "修改失败");
        }
        setModuleEdit(model);
        model.addAttribute(Web.OBJ, obj);
        return getUrlBase().concat("-edit");
    }

    /**
     * 根据传入的数据ids,来删除对象.
     */
    @PostMapping(value = Web.URL_SEP_REMOVE)
    @ResponseBody
    protected JsonVo remove(@RequestBody DeleteVo<Long> dvo) {
        try {
            if (dvo != null && dvo.getIds() != null && dvo.getIds().size() > 0) {
                return super.remove(dvo);
            }
            return new JsonVo(true);
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("remove error ", e);
            return new JsonVo(false, "删除失败");
        }
    }
}
